package com.springspirit.framework.logging;

import java.util.List;
import java.util.UUID;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.springspirit.framework.message.LogMessage;

/**
 * 로그 컴포넌트
 * 
 * 비즈니스 예외, 오류를 로깅한다.
 * 
 * @author greatshin
 * 
 */
@Service("logAppender")
public class LogAppender {
	
//	@Autowired
	private DataSource dataSource;
	
	private JdbcTemplate jdbcTemplate;

	public List getLogs() {
		return jdbcTemplate.queryForList("select * from monitor");
	}
	
	public List getLogCount() {
		
		String sql = "select substring(timeStamp,1,16) , count(*) as count " +
					 "from monitor " +
					 "group by substring(timeStamp,1,16) ";
		
		return jdbcTemplate.queryForList(sql);
	}
	
	public void insertLog(LogMessage logMessage){
		
		UUID uid = UUID.randomUUID();
		
		jdbcTemplate.update("insert into monitor(id, no, loginUser, loginIpAddress, " +
							"subSystem, menu, responsePerson, layer, errorCategory, errorMessage, timeStamp) " +
							"values(?,?,?,?,?,?,?,?,?,?,?)",
						uid.toString(),
						logMessage.getNo(),
						logMessage.getLoginUser(),
						logMessage.getLoginIpAddress(),
						logMessage.getSubSystem(),
						logMessage.getMenu(),
						logMessage.getResponsePerson(),
						logMessage.getLayer(),
						logMessage.getErrorCategory(),
						logMessage.getErrorMessage(),
						logMessage.getTimeStamp());
	}

	public DataSource getDataSource() {
		return dataSource;
	}
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
		this.jdbcTemplate = jdbcTemplate;
	}

	@Autowired
	public void setDataSource(DataSource dataSource) {
//		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

}
